<!--
 * @Description: app端跳转订单详情
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="container">
    <view style="display: flex; justify-content: flex-end; margin: 20rpx">
      <!-- 重新加载图标 -->
      <u-icon
        name="reload"
        size="40"
        @click="getOrderInfo"
        style="cursor: pointer"
      ></u-icon>
    </view>
    <view @click="handleClickItem(orderInfo)">
      <view class="top">
        <view class="ddbox">
          <text style="color: #1a73e8">{{
            handleText(orderInfo.status, orderInfo.orderThirdParty.orderStatus)
          }}</text></view
        >
        <view class="ypbox">
          <view class="ypbox-l">
            <van-image
              width="100%"
              height="232rpx"
              :src="orderInfo.orderThirdParty.posterUrl"
            />
          </view>
          <view class="ypbox-r">
            <view class="nr">
              <view class="bt overwz">
                {{ orderInfo.orderThirdParty.movieName }}
              </view>
              <view class="xq">
                <view>{{ orderInfo.orderThirdParty.showTime }}</view>
                <view class="overwz">{{
                  orderInfo.orderThirdParty.cinemaName
                }}</view>
                <view class="overwz"
                  >{{ orderInfo.orderThirdParty.hallName }}
                </view>
                <view style="color: #19be6b">
                  {{
                    orderInfo.orderThirdParty.seatsInfos.replaceAll('列', '座')
                  }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view
          v-if="orderInfo.orderThirdParty.cinemaClose == 1"
          style="color: red"
        >
          <text style="margin-right: 20rpx">
            该订单因渠道或者影院信息调整等特殊原因失效会导致取票失败，请联系人工客服进行退款。</text
          >
          <u-button
            type="success"
            size="mini"
            @click="handleCallPhone(orderInfo)"
            >联系客服</u-button
          >
        </view>
        <view
          style="color: red"
          v-if="orderInfo.status == 20 || orderInfo.status == 60"
        >
          <text style="margin-right: 20rpx">
            退款提示：用户需先联系电影院释放座位，之后联系平台申请退款。</text
          >
        </view>
      </view>
      <view class="middle">
        <view style="font-weight: bold; font-size: 30rpx; margin-bottom: 10rpx"
          >共{{ orderInfo.orderProductSkus.length }}张电影票</view
        >
        <view class="middle-t">
          <view>
            <view>总价</view>
            <view class="hswz">￥{{ orderInfo.totalMoney }}</view>
          </view>
          <view>
            <view> {{ enumAll.SHOPMODEL[orderInfo.shopMode] }}抵扣 </view>
            <text class="hswz"> ￥{{ orderInfo.scoreMoney }}</text>
          </view>
          <view v-if="orderInfo.shopMode == 4 || orderInfo.shopMode == 6">
            <text>服务费</text>
            <view class="hswz">￥{{ orderInfo.otherMoney }}</view>
          </view>
          <view>
            <text>{{ handleFkwz(orderInfo.status) }}</text>
            <view>
              <text class="hswz"
                >￥{{ orderInfo.totalMoney - orderInfo.scoreMoney }}</text
              ></view
            >
          </view>
          <view
            >购买手机号
            <text class="hswz">{{ orderInfo.contactNumber }}</text></view
          >
          <view
            >购买时间
            <text class="hswz">{{
              formatTimestamp(orderInfo.createTime)
            }}</text></view
          >
          <view
            >订单编号<text class="hswz">{{ orderInfo.orderNo }}</text>
            <view>
              <van-button
                plain
                hairline
                size="small"
                type="default"
                @click="handleCopy"
                >复制</van-button
              >
            </view>
          </view>
        </view>
        <view class="middle-b">
          <!-- <view>
            <u-button
              v-if="orderInfo.status == 10"
              size="medium"
              type="warning"
              style="background-color: greenyellow"
              @click="handlePay(orderInfo)"
              >去支付</u-button
            >
          </view> -->
          <view>
            <u-button
              v-if="orderInfo.status == 60 && !orderInfo.isfy"
              size="medium"
              type="warning"
              @click="handleGoDetail(orderInfo)"
              >去取票</u-button
            >
            <u-button
              v-if="orderInfo.status == 60 && orderInfo.isfy"
              size="medium"
              type="warning"
              style="background-color: #1a73e8"
              @click="handleGoDetail(orderInfo)"
            >
              查看已取票信息</u-button
            >
          </view>
          <view
            v-if="
              (orderInfo.orderThirdParty.orderStatus == 'CLOSE' &&
                orderInfo.status == 20) ||
              (orderInfo.orderThirdParty.orderStatus == 'GENERATE_FAIL' &&
                orderInfo.status == 20)
            "
          >
            <u-button
              size="medium"
              type="error"
              @click="handleRefund(orderInfo.id)"
              >发起退款</u-button
            >
          </view>
        </view>
      </view>
      <view class="footer"> </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { formatTimestamp } from '@/utils/index'
import { movieApi, moneyApi, orderApi, enumAll } from '@/api'
import { storeToRefs } from 'pinia'
import debounce from 'lodash/debounce'
import { Decimal } from 'decimal.js'
import { browserVersion } from '@/utils/common'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { useUserStore, useMovieStore, useShopInfoStore } from '@/store'
import { calculateStopShowTime } from '../../components/movieUtil'
const userStore = useUserStore()
const shopStore = useShopInfoStore()
const shopInfoStore = useShopInfoStore()
const { accessToken, useShareCode } = storeToRefs(userStore)
const isApp = ref(false)
const orderId = ref<any>(0)
const orderInfo = ref<any>({
  orderThirdParty: { seatsInfos: '' },
  orderProductSkus: []
})
const movieStore = useMovieStore()
// 所有的模式
const shopTypeAllList = ref([
  { name: '黑银', id: 0 },
  { name: '花积分', id: 1 },
  { name: '链动模式', id: 2 },
  { name: '酒慕网', id: 3 },
  { name: '鑫复来', id: 4 },
  { name: '长来科技', id: 6 }
])

// 页面加载时检查协议状态
onLoad(async (option: any) => {
  // console.log('订单接收option', option)
  orderId.value = option.orderId
  if (option?.from && option.from.toLowerCase() === 'app') {
    isApp.value = true
  }
  if (orderId.value) {
    getOrderInfo()
  }
})
onShow(() => {})
//获取单个订单数据
const getOrderInfo = async () => {
  const nowTime = new Date() // 获取当前时间
  uni.showLoading({ title: '获取订单信息中，请稍后', mask: true })
  try {
    let tempObj = {
      detail: true,
      integralsRuleId: 7,
      orderNo: orderId.value
    }
    const { data } = await orderApi.orderList(tempObj).finally(() => {
      uni.hideLoading()
    })
    let tempArr = data.records.map((ele: any) => {
      //已出票的才加isfy字段
      if (ele.status === 60) {
        // 计算散场时间
        const stopShowTimeStr = calculateStopShowTime(
          ele.orderThirdParty.showTime,
          ele.orderThirdParty.duration
        )
        // 将字符串转换为 Date 对象进行比较
        const stopShowTime = new Date(stopShowTimeStr.replace(' ', 'T'))
        const isfy = nowTime > stopShowTime ? true : false
        return {
          ...ele,
          isfy
        }
      }
      // 非 status=60 的情况直接返回原对象
      return ele
    })
    console.log('获取单个订单', data)
    orderInfo.value = tempArr[0]
  } catch (e) {
    console.log('获取orderInfo错误', e)
  }
}
const handleCopy = () => {
  const orderNo = orderInfo.value.orderNo
  if (orderNo) {
    uni.setClipboardData({
      data: orderNo,
      success: () => {
        uni.showToast({ title: '复制成功' })
      },
      fail: () => {
        uni.showToast({ title: '复制失败', icon: 'none' })
      }
    })
  } else {
    uni.showToast({ title: '订单编号为空', icon: 'none' })
  }
}
// 处理付款文字
const handleFkwz = (zt: any) => {
  let str = ''
  switch (zt) {
    case 10:
      str = '待付款'
      break
    case 90:
    case 91:
      str = '应付款'
      break
    default:
      str = '实付款'
  }
  return str
}
// 处理文字
const handleText = (zt: any, ddzt: any) => {
  let str = ''
  switch (zt) {
    case 10:
      str = '待支付'
      break
    case 20:
      str = '待出票'
      break
    case 60:
      str = '已出票'
      break
    case 90:
    case 91:
    case 70:
      str = '已取消'
      break
    case 92:
      str = '已退款'
      break
  }
  if ((zt == 20 && ddzt == 'CLOSE') || (zt == 20 && ddzt == 'GENERATE_FAIL')) {
    str = '出票失败'
  }

  return str
}
// 点击去支付
const handlePay = (ddItem: any) => {
  // console.log('dd', ddItem)
  if (ddItem) {
    if (isApp.value) {
      const u = browserVersion()
      if (u.iPhone) {
        // @ts-ignore
        window.JSBridge.invoke('goPay', {
          orderId: ddItem.id,
          money: ddItem.payMoney
        })
        shopInfoStore.setIsApp(false)
        return
      } else if (u.isAndroid) {
        // @ts-ignore
        if (window?.Android) {
          // @ts-ignore
          window?.Android?.goPay(ddItem.id, ddItem.payMoney)
          shopInfoStore.setIsApp(false)
        }
        return
      }
    } else {
      location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${ddItem.id}`
    }
  }
}
// 点击去取票
const handleGoDetail = (ddItem: any) => {
  // console.log('订单详情取票', ddItem)
  // 存储模式
  const modeArr = shopTypeAllList.value.filter(
    (item) => item.id == ddItem.shopMode
  )
  // console.log(JSON.stringify(modeArr[0]), modeArr)
  uni.setStorageSync('hyType', JSON.stringify(modeArr[0]))
  movieStore.setSelectedOrder(ddItem)
  uni.navigateTo({ url: `/packageF/pages/ticketCodeDetails/index` })
}
// 点击退票
const handleRefund = (ddid: any) => {
  uni.showModal({
    title: '提示',
    content:
      '是否确定要退款?(退款不会立即到账,系统最晚会在1-2天内提交客服支付处理)',
    success({ confirm, cancel }) {
      if (confirm) {
        const { data, code, msg } = orderApi.orderUpdate({
          id: ddid,
          status: 92
        })
        // console.log(data, code, '退款详情')
        if (code) {
          if (code == 200) {
            uni.showToast({
              title: '退款成功'
            })
          } else {
            uni.showToast({
              icon: 'error',
              title: `退款失败请稍后重试`
            })
          }
        }

        setTimeout(() => {
          //刷新
          getOrderInfo()
        }, 5000)
      } else {
        console.log('取消')
      }
    }
  })
}
// 点击盒子
const handleClickItem = (ddItem: any) => {
  // console.log('dd', ddItem)
  // 已出票的情况跳转取票详情页面
  if (ddItem.status == 60) {
    handleGoDetail(ddItem)
  }
}
// 点击联系客服
const handleCallPhone = (ddItem: any) => {
  let phone = ''
  switch (ddItem.shopMode) {
    case 1:
      phone = '13808042693'
      break
    case 4:
      phone = '18349389439'
      break
    case 6:
      phone = '19141914176'
  }
  // 判断是否为 H5 端
  if (uni.getSystemInfoSync().platform === 'web') {
    // 复制号码到剪贴板
    uni.setClipboardData({
      data: phone,
      success: () => {
        uni.showToast({ title: '号码已复制，请手动拨号', icon: 'none' })
      }
    })
  } else {
    // 非 H5 端，正常唤起拨号
    uni.makePhoneCall({ phoneNumber: phone })
  }
}
</script>

<style lang="scss" scoped>
.container {
  font-size: 24rpx;
  .top {
    width: 702rpx;
    // height: 380rpx;
    background: #ffffff;
    border-radius: 8rpx;
    margin: 0 auto;
    padding: 20rpx;
    margin-top: 20rpx;
    margin-bottom: 30rpx;
    .ddbox {
      display: flex;
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
      text-align: right;
      justify-content: flex-end;
    }
    .ypbox {
      display: flex;
      align-items: center;
      margin-bottom: 50rpx;
      .ypbox-l {
        width: 162rpx;
        height: 232rpx;
        border: 1rpx solid #dbdbdbdb;
        border-radius: 5rpx;
        margin-right: 20rpx;
      }
      .ypbox-r {
        flex-grow: 1;
        height: 232rpx;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        .nr {
          height: 100%;
          width: 0rpx;
          flex-grow: 1;
          margin-right: 20rpx;
          .bt {
            font-size: 32rpx;
            color: #000;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          .xq {
            > view {
              margin-bottom: 10rpx;
              color: #333;
            }
          }
        }
      }
    }
    .tsbox {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .middle {
    width: 702rpx;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 10rpx;
    padding: 20rpx;
    .middle-t {
      font-size: 28rpx;
      color: #111;
      font-weight: 400;
      > view {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20rpx;
        height: 40rpx;
      }
    }
    .middle-b {
      padding-top: 20rpx;
      text-align: right;
    }
  }
  .footer {
    width: 750rpx;
    height: 144rpx;
    // background: #ffffff;
    text-align: right;
    padding: 20rpx;
  }
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
.jcwz {
  font-size: 24rpx;
  font-weight: bold;
  color: #000;
}
.hswz {
  color: #999;
}
</style>
